package chapter4.lessons;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Project ：learn_java
 * @File ：SellTicketDemoSolve01.java
 * @IDE ：IntelliJ IDEA
 * @Author ：自由如风间
 * @Date ：2025/3/5 21:36
 * @Description ：资源竞争的原子性解决方案
 */

public class SellTicketDemoSolve01 implements Runnable {

    private int tickets = 100;
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            lock.lock();
            try {
                if (tickets <= 0) break;
                tickets--;
                System.out.println(Thread.currentThread().getName()
                        + " 在卖票，余 " + tickets + " 票");
            } finally {
                lock.unlock();
            }
        }
    }
}
